<?php

namespace App\Services\Applet\Sponsor;

use App\Exceptions\SponsorException;
use App\Helpers\MvcHelper;
use App\Models\Applet\Sponsor\UserSlaughterRecordsModel;
use Exception;
use Illuminate\Support\Facades\DB;

class SlaughterService extends BaseSponsorService
{

    /**
     * 申请宰杀
     * @return void
     * @throws Exception
     */
    public function create(array $params)
    {
        // 查询用户认养记录
        $userSponsor = $this->getUserSponsorModel()->getItemsByIdAndUserId($params['id'], MvcHelper::getLoginUserId(), [
            'id', 'user_id'
        ]);
        if (empty($userSponsor)) {
            throw new SponsorException('用户认养记录不存在', SponsorException::CODE_4001);
        }

        // 查询是否已提交申请
        $userSlaughter = $this->getUserSlaughterRecordsModel()->getItemByUserIdAndUserSponsorId($userSponsor['user_id'], $userSponsor['id']);
        if (!empty($userSlaughter)) {
            throw new SponsorException('申请已提交，请耐心等候', SponsorException::CODE_5002);
        }

        $createUserSlaughter = [
            'user_id' => $userSponsor['user_id'],
            'user_sponsor_id' => $userSponsor['id'],
            'user_address_id' => $params['userAddressId'] ?? 0,
            'type' => $params['type'],
        ];

        // 查询用户收货地址
        $createUserAddressData = [];
        if ($params['type'] == UserSlaughterRecordsModel::TYPE_SEND_BACK) {
            $userAddress = $this->getUserAddressModel()->getItemByUserIdAndId(MvcHelper::getLoginUserId(), $params['userAddressId'], [
                'id', 'user_id', 'receive_name', 'receive_tel', 'area_info', 'address', 'province_id', 'city_id', 'region_id'
            ]);

            $createUserAddressData = [
                'user_id' => $userSponsor['user_id'],
                'user_address_id' => $params['userAddressId'],
                'user_slaughter_id' => 0,
                'receive_name' => $userAddress['receive_name'],
                'receive_tel' => $userAddress['receive_tel'],
                'area_info' => $userAddress['area_info'],
                'address' => $userAddress['address'],
                'province_id' => $userAddress['province_id'],
                'city_id' => $userAddress['city_id'],
                'region_id' => $userAddress['region_id'],
            ];
        }

        DB::transaction(function () use ($createUserSlaughter, $createUserAddressData) {
            $userSlaughterId = $this->getUserSlaughterRecordsModel()->addItemGetId($createUserSlaughter);

            if (!empty($createUserAddressData)) {
                $createUserAddressData['user_slaughter_id'] = $userSlaughterId;
                $this->getUserSlaughterAddressModel()->addItem($createUserAddressData);
            }
        });
    }

}
